package com.ai.trickycards.ui.dialog

import android.app.Dialog
import android.content.Context
import android.content.res.ColorStateList
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import com.ai.trickycards.AppViewModel
import com.ai.trickycards.Constant
import com.ai.trickycards.databinding.DialogCheckInBinding
import com.ai.trickycards.entity.enumeration.LevelRangeEnum
import com.ai.trickycards.utils.SP
import com.ai.trickycards.utils.Utils
import java.text.SimpleDateFormat
import java.util.Locale

class CheckInDialog(
    context: Context,
    private val appViewModel: AppViewModel
) : Dialog(context) {

    private val binding by lazy {
        DialogCheckInBinding.inflate(layoutInflater)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(binding.root)
        setCanceledOnTouchOutside(false)
        setCancelable(false)
        window?.let {
            it.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
            val displayMetrics = context.resources.displayMetrics
            it.attributes.width = (displayMetrics.widthPixels - 48 * displayMetrics.density).toInt()
        }

        val checkInSet = SP.getInstance(context).getStringSet(Constant.SP_KEY.CHECK_IN, emptySet())!!
        val today = Utils.today()
        if (checkInSet.contains(today)) {
            binding.tvClaim.isEnabled = false
            binding.tvClaim.backgroundTintList = ColorStateList.valueOf(Color.parseColor("#CCCCCC"))
            binding.tvClaim.setTextColor(Color.parseColor("#999999"))
            setCanceledOnTouchOutside(true)
        }

        val userInfo = appViewModel.userInfoFlow.value.copy()
        // 每日签到的积分奖励固定为该等级下默认积分的1/10
        val checkInScore = (Utils.getLevelRange(userInfo.level).levelScore * 0.1).toInt()
        binding.tvScore.text = "$checkInScore"

        binding.tvClaim.setOnClickListener {
            it.isEnabled = false
            dismiss()
            val mutableSet = checkInSet.toMutableSet()
            mutableSet.add(today)
            SP.getInstance(context).edit().putStringSet(Constant.SP_KEY.CHECK_IN, mutableSet).apply()

            userInfo.score += checkInScore
            appViewModel.changeUserInfo(userInfo)
        }
    }
}